package com.leyou.page.scheduler;

import com.leyou.auth.client.AuthClient;
import com.leyou.page.config.JwtProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 服务Token定时获取任务
 */
@Component
@Slf4j
public class AppTokenScheduler {
    @Autowired
    private AuthClient authClient;
    @Autowired
    private JwtProperties jwtProps;

    //设计一个变量用于申请到的服务token
    private String appToken;

    /**
     * token刷新间隔
     */
    private static final long TOKEN_REFRESH_INTERVAL = 86400000L; //24小时

    /**
     * token获取失败后重试的间隔
     */
    private static final long TOKEN_RETRY_INTERVAL = 10000L;
    /**
     * 每隔1天定时获取服务token
     */
    @Scheduled(fixedRate = TOKEN_REFRESH_INTERVAL )
    public void appTokenGet(){

        while(true) {
            try {
                //请求授权中心申请合法的服务Token
                String appToken = authClient.authorization(jwtProps.getApp().getServiceName(), jwtProps.getApp().getSecret());

                //赋值服务token
                this.appToken = appToken;

                log.info("【服务token申请】"+jwtProps.getApp().getServiceName()+"申请成功");

                //如果申请成功，则退出
                break;
            } catch (Exception e) {
                log.error("【服务token申请】申请失败，10秒后重试");

                //等待10秒后重新申请
                try {
                    Thread.sleep(TOKEN_RETRY_INTERVAL);
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
            }

        }
    }


    //给外部获取服务token
    public String getAppToken() {
        return appToken;
    }
}
